import { useWebSiteStore } from '@/store/web/site'
import { useWebUploadStore } from '@/store/web/upload'
import { getValueFromXml, randomUploadFileName } from '@/utils/'
import { MOBILE_WID_HEI } from '@/const/'
import { fileUploadUrl } from '@/service/web/api'

export class CoverImg {
  constructor() {
    this.print()
  }

  dataURLToBlob(dataURL: any) {
    var BASE64_MARKER = ';base64,';
    var raw: any;
    var contentType: any;
    var parts: any;
    if (dataURL.indexOf(BASE64_MARKER) == -1) {
        parts = dataURL.split(',');
        contentType = parts[0].split(':')[1];
        raw = decodeURIComponent(parts[1]);

        return new Blob([raw], {type: contentType});
    }

    parts = dataURL.split(BASE64_MARKER);
    contentType = parts[0].split(':')[1];
    raw = window.atob(parts[1]);
    var rawLength = raw.length;

    var uInt8Array = new Uint8Array(rawLength);

    for (var i = 0; i < rawLength; ++i) {
      uInt8Array[i] = raw.charCodeAt(i);
    }

    return new Blob([uInt8Array], {type: contentType});
  }
  print() {
    const useWebUpload = useWebUploadStore()
    const useWebSite = useWebSiteStore()
    const fileUploadData: any = _.cloneDeep(useWebUpload.fileUploadData)
    const el = document.getElementsByClassName("drag-edit-zone-style")[0]
    const canvasDoms = el.querySelectorAll('canvas')
    _.forEach(canvasDoms, (canvasDom: any) => {
      canvasDom.style.display = "none"
    })
    window.html2canvas(el,{
      useCORS: true,
      async: true,
      logging: false,
      scale: 0.5,
      // allowTaint: true,
      width: MOBILE_WID_HEI.width/2,
      height: MOBILE_WID_HEI.height/2,
    }).then( (canvas: any) => {
      _.forEach(canvasDoms, (canvasDom: any) => {
        canvasDom.style.display = "block"
      })
      canvas.toBlob((blobObj: any) => {
        const filename = randomUploadFileName(Number(useWebSite.id)) + ".jpeg"
        fileUploadData.key += filename
        const option = {
          action: fileUploadUrl,
          onSuccess: this.onSuccess,
          onError: this.onError,
          data: fileUploadData,
          fileKey: "file",
          file: blobObj,
        }
        this.upload(option)
      }, "image/jpeg", 0.8)
    })
  }
  upload(option: any){
    var xhr = new XMLHttpRequest()
    var action = option.action
    var formData = new FormData()
    if (option.data) {
      Object.keys(option.data).forEach( (key) => {
        formData.append(key, option.data[key])
      });
    }
    formData.append(option.fileKey, option.file)
    xhr.onerror = (e) => {
      option.onError(e)
    };
    xhr.onload = () => {
      if (xhr.status < 200 || xhr.status >= 300) {
        return option.onError(this.getError(action, option, xhr))
      }
      option.onSuccess(this.getBody(xhr))
    };
    xhr.open('post', action, true)
    var headers = option.headers || {}
    for (var key in headers) {
      if (Object.prototype.hasOwnProperty.call(headers, key) && headers[key] !== null) {
        xhr.setRequestHeader(key, headers[key])
      }
    }
    xhr.send(formData)
    return xhr
  }
  onSuccess(response: any){
    let url = getValueFromXml(response)
    url = _.replace(url, 'http', 'https')
    url = _.replace(url, 'file', 'static')
    url = _.replace(url, '.s3.sinaapp.com', '')
    
    const useWebSite = useWebSiteStore()
    useWebSite.updateSiteAttrs({ thumb: url })
    useWebSite.saveSiteDatas()
  }
  getBody(xhr: any) {
    var text = xhr.responseText || xhr.response
    if (!text) {
      return text
    }
    try {
      return JSON.parse(text)
    } catch (e) {
      return text
    }
  }
  getError(action: any, option: any, xhr: any) {
    var msg: string = ''
    if (xhr.response) {
      msg = '' + (xhr.response.error || xhr.response)
    } else if (xhr.responseText) {
      msg = '' + xhr.responseText
    } else {
      msg = 'fail to post ' + action + ' ' + xhr.status
    }
    var err: any = new Error(msg)
    err.status = xhr.status
    err.method = 'post'
    err.url = action
    return err
  }
  onError(e: any){
    console.log(e);
  }
}